package servlet;

import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(value = "/Houduanshujuku")


public class houduanshujuku extends HttpServlet
{
    //与前端交互部分
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException
    {
        String picname= req.getParameter("picname");
        String picauthor=req.getParameter("picauthor");
        String picintroduction=req.getParameter("picintroduction");
        String pictag=req.getParameter("pictag");
        String picsource=req.getParameter("picsource");

        System.out.println(picname+','+picauthor);

        //调用函数上传数据
        writeFileToMySQL(picname,picauthor,picintroduction,picsource,pictag);
    }



    //定义方法把文件写入MySQL数据库
    public static void writeFileToMySQL(String picname,String picauthor,String picintroduction,String picsource,String pictag)
    {
        Connection connPictures=null;
        PreparedStatement ps=null;
        PreparedStatement psTags=null;
        PreparedStatement psId=null;
        int result = 0;
        int resulttags=0;

        JdbcTemplate jdbcTemplate =  new JdbcTemplate(JDBCUtils.getDataSource());
        String sql="INSERT INTO pictures(picname,picauthor,picintroduction,pictures) VALUES (?,?,?,?)";
        jdbcTemplate.update(sql,picname,picauthor,picintroduction,picsource);

        //切分标签
        String pictagArr[]=pictag.split(",");
        String sqlgetID = "select picid from pictures where picauthor=? and picintroduction=? and picname=? and pictures=?";
        String picid = jdbcTemplate.queryForObject(sqlgetID,String.class,picauthor,picintroduction,picname,picsource);


        String sqlInsert = "insert into picturetag(picid,pictag,tagid) values(?,?,?)";
        for (int i=0;i<pictagArr.length;i++){
            jdbcTemplate.update(sqlInsert,picid,pictagArr[i],i);
        }


    }
}

